package net.tv90.bfmccoreqqbot.api;


import net.tv90.bfmccoreqqbot.api.annotation.MessageType;
import net.tv90.bfmccoreqqbot.api.entity.MessageContext;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

public class AnnotationBasedMessageDispatcher extends AbstractMessageDispatcher {

    public void registerHandlersFromPackage(String packageName) {
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);

            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                if (resource.getProtocol().equals("file")) {
                    File directory = new File(resource.toURI());
                    scanClassesInDirectory(packageName, directory);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void scanClassesInDirectory(String packageName, File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    scanClassesInDirectory(packageName + "." + file.getName(), file);
                } else if (file.getName().endsWith(".class")) {
                    String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6);
                    try {
                        Class<?> clazz = Class.forName(className);
                        registerAnnotatedHandler(clazz);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void registerAnnotatedHandler(Class<?> clazz) {
        MessageType annotation = clazz.getAnnotation(MessageType.class);
        if (annotation != null && MessageHandler.class.isAssignableFrom(clazz)) {
            String messageType = annotation.value();
            register(messageType, clazz.asSubclass(MessageHandler.class));
        }
    }

    @Override
    public void dispatch(MessageContext msg) {
        super.dispatch(msg);
    }

    @Override
    public void registerHandler(String messageType, Class<? extends MessageHandler> handlerClass) {

    }

}
